Binary Tree Paths

Given a binary tree, return all root-to-leaf paths.

For example, given the following binary tree:

  1. 1
  2. / \
  3. 2 3
  4. \
  5. 5

All root-to-leaf paths are:

  1. ["1->2->5", "1->3"]

Solution:

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. public class Solution {
  11. public List<String> binaryTreePaths(TreeNode root) {
  12. List<String> res = new ArrayList<String>();
  13. helper(root, new ArrayList<Integer>(), res);
  14. return res;
  15. }
  16. void helper(TreeNode root, List<Integer> sol, List<String> res) {
  17. if (root == null) return;
  18. sol.add(root.val);
  19. if (root.left == null && root.right == null) {
  20. res.add(convert(sol));
  21. } else {
  22. helper(root.left, sol, res);
  23. helper(root.right, sol, res);
  24. }
  25. sol.remove(sol.size() - 1);
  26. }
  27. String convert(List<Integer> list) {
  28. StringBuilder sb = new StringBuilder();
  29. for (int i = 0; i < list.size(); i++) {
  30. if (i > 0) sb.append("->");
  31. sb.append(list.get(i));
  32. }
  33. return sb.toString();
  34. }
  35. }